package com.itheima.tlias.controller;

import com.itheima.tlias.dto.SelectEmpDTO;
import com.itheima.tlias.dto.SelectEmpDetailDTO;
import com.itheima.tlias.entity.Exe;
import com.itheima.tlias.mapper.ExeMapper;
import com.itheima.tlias.po.InsertEmpParam;
import com.itheima.tlias.po.SelectEmpPageParam;
import com.itheima.tlias.po.UpdateEmpParam;
import com.itheima.tlias.service.EmpService;
import com.itheima.tlias.util.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;

/**
 * 员工controller
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Resource
    EmpService empService;

    @Resource
    ExeMapper exeMapper;

    @GetMapping
    public ResultUtil empService(SelectEmpPageParam param) {
        if (Objects.isNull(param.getPage()) || Objects.isNull(param.getPageSize())) {
            return ResultUtil.fail("分页参数不存在");
        }
        return empService.selectEmpByPage(param);
    }

    @DeleteMapping
    public ResultUtil batchDelete(@RequestParam("ids") List<Integer> ids) {
        if (ids.isEmpty()) {
            return ResultUtil.fail("请先选择要删除的信息");
        }
        int flag = empService.batchDelete(ids);
        return ResultUtil.success(flag);
    }

    @PostMapping
    public ResultUtil insertEmp(@Validated @RequestBody InsertEmpParam param) {
        int flag = empService.insertEmp(param);
        return flag == 0 ? ResultUtil.fail("添加失败") : ResultUtil.success("添加成功");
    }

    @GetMapping("/{id}")
    public ResultUtil selectEmpById(@PathVariable("id") Integer id) {
        //先查询信息
        SelectEmpDetailDTO dto = empService.selectEmpById(id);
        //再查询履历
        List<Exe> exes = exeMapper.selectExeByEmpId(id);
        dto.setExprList(exes);
        return ResultUtil.success(dto);
    }

    @PutMapping
    public ResultUtil updateEmp(@RequestBody UpdateEmpParam param) {
        int flag = empService.updateEmp(param);
        return flag == 0 ? ResultUtil.fail("修改失败") : ResultUtil.success("修改成功");
    }

    @GetMapping("/list")
    public ResultUtil selectAllMaster(){
        List<SelectEmpDTO> dtos = empService.selectAllMaster();
        return ResultUtil.success(dtos);
    }

}
